import { defineComponent, reactive } from "vue";
import styles from "./modifyField.module.less";
import { EditOutlined } from "@ant-design/icons-vue";
const lessVars = require("@/styles/var");
export default defineComponent({
  props: {
    label: {
      type: String,
      required: true,
    },
    modelValue: {
      type: String,
    },
    placeholder: {
      type: String,
      default: "暂未设置",
    },
    type: {
      type: String,
      default: "input",
    },
  },
  emits: ["update:modelValue", "confirm"],
  setup(props, { emit }) {
    const state = reactive({
      inputValue: "",
      isEdit: false,
      editing: false,
      edit() {
        state.isEdit = true;
        state.inputValue = props.modelValue;
      },
      editConfirm() {
        state.editing = true;
        emit("confirm", {
          value: state.inputValue,
          success:state.editConfirmSuccess,
          fail:state.editConfirmFail,
          complete:state.editConfirmComplete,
        });
      },
      editCancel() {
        state.inputValue = "";
        state.isEdit = false;
      },
      editConfirmFail() {
        state.editConfirmComplete();
      },
      editConfirmComplete() {
        state.editing = false;
      },
      editConfirmSuccess() {
        state.isEdit = false;
        state.editConfirmComplete();
        emit("update:modelValue", state.inputValue);
      },
    } as any);

    const ModifyField = () => (
      <div class={styles.row}>
        <span class={styles.label}>{props.label}</span>
        {!state.isEdit ? (
          <>
            <span
              class={[!props.modelValue ? styles.placeholder : styles.text]}
            >
              {props.modelValue || props.placeholder}
            </span>
            <EditOutlined
              style={{
                marginLeft: "10px",
                color: lessVars["primary-color"],
                cursor: "pointer",
              }}
              onClick={() => state.edit()}
            />
          </>
        ) : (
          <>
            {props.type === "textarea" ? (
              <a-textarea
                v-model:value={state.inputValue}
                style={{ flex: "1", maxWidth: "240px" }}
                placeholder={`请输入${props.label}`}
              />
            ) : (
              <a-input
                v-model:value={state.inputValue}
                style={{ flex: "1", maxWidth: "240px" }}
                placeholder={`请输入${props.label}`}
              />
            )}
            <a-button
              type="link"
              size="small"
              loading={state.editing}
              onClick={() => state.editConfirm()}
            >
              确定
            </a-button>
            <a-button
              type="text"
              size="small"
              onClick={() => state.editCancel()}
            >
              取消
            </a-button>
          </>
        )}
      </div>
    );
    return () => <ModifyField />;
  },
});
